package es.abredatos.client.presenter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HTMLTable.Cell;

import es.abredatos.client.BooksLocatorServiceAsync;
import es.abredatos.client.event.GetBookDetailsEvent;
import es.abredatos.client.event.GoHomeEvent;
import es.abredatos.shared.Book;

public class BooksPresenter implements Presenter {

	public interface Display {
		HasClickHandlers getNewSearchButton();

		void setRows(List<String> rows);

		HasClickHandlers getSelectedItem();
	}

	private BooksLocatorServiceAsync rpcService;
	private HandlerManager eventBus;
	private Display display;
	private String title;

	public BooksPresenter(BooksLocatorServiceAsync rpcService, HandlerManager eventBus, Display display, String title) {
		this.rpcService = rpcService;
		this.eventBus = eventBus;
		this.display = display;
		this.title = title;
	}

	public void go(HasWidgets container) {
		container.clear();
		container.add((Widget) display);

		bind();

		fetchBooks();

	}

	private void bind() {
		display.getSelectedItem().addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent event) {
				// FIXME: Obtener el id seleccionado de otro modo
				Cell cell = ((FlexTable) event.getSource()).getCellForEvent(event);
				String id = String.valueOf(cell.getCellIndex());
				eventBus.fireEvent(new GetBookDetailsEvent(id));
			}
		});

		display.getNewSearchButton().addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent event) {
				eventBus.fireEvent(new GoHomeEvent());
			}
		});
	}

	private void fetchBooks() {
		rpcService.searchBook(title, "", false, 0, 0, new AsyncCallback<List<Book>>() {

			public void onSuccess(List<Book> books) {

				List<String> titles = new ArrayList<String>();

				for (Iterator<Book> iterator = books.iterator(); iterator.hasNext();) {
					Book book = iterator.next();

					titles.add(book.getTitle());
				}

				display.setRows(titles);
			}

			public void onFailure(Throwable caught) {
				Window.alert("Communication fail");
			}
		});
	}

}
